#encoding: utf-8
'''
Created on 2012-9-17

@author: Administrator
'''

from DbOperator import DbOperator
from User import User
from UserFriendsRelation import UserFriendsRelation
from pub import Func
from pub.Config import Config
class UserModel(DbOperator):
    '''
    用户逻辑操作
    '''
    def __init__(self,):
        '''
        Constructor
        '''
        DbOperator.__init__(self)
   
    
    
    def getUserInfoByKeyword(self, keyword,user=None):
        '''
        取用户详情
        '''
        tmp = None
        Fields = ('Id', 'UserName', 'UserPass', 'UserLevel', 'UserCash', 'UserPhoto', 'UserState',
                  'UserLoginPosX', 'UserLoginPosY', 'UserEmail', 'UserTel', 'UserAge', 'UserBirth',
                  'UserSign', 'UserSex', 'UserNickName', 'Created', 'UserLastLoginIp', 'UserLastLoginTime',
                  'UserIsOnline', 'checkFlag', 'searchFlag', 'UserProvince', 'UserArea'
                  )
        aParam = {
                  Config.S_TABLE:User.TABLE_NAME,
                  Config.S_SEARCHFIELDS:",".join(Fields),
                  Config.S_SEARCHCONDITION:" (UserName='%s' or UserNickName='%s' or UserEmail='%s' or UserTel='%s')" % (keyword,keyword,keyword,keyword),
                  Config.S_RESULTROW:1,
                  }
        
        result = self.getFieldByCondition(aParam)
        if(result != None):
            if not user:            
                oUser = User();
            else:
                oUser=user;
            oUser.set_user_id(result[User.USERID])  
            oUser.set_user_name(result[User.USERNAME])  
            oUser.set_user_pass(result[User.USERPASS])  
            oUser.set_user_level(result[User.USERLEVEL])  
            oUser.set_user_cash(result[User.USERCASH])  
            oUser.set_user_photo(result[User.USERPHOTO])  
            oUser.set_user_state(result[User.USERSTATE])  
            oUser.set_user_login_pos_x(result[User.USERLOGINPOSX])  
            oUser.set_user_login_pos_y(result[User.USERLOGINPOSY])  
            oUser.set_user_email(result[User.USEREMAIL])  
            oUser.set_user_tel(result[User.USERTEL])  
            oUser.set_user_age(result[User.USERAGE])  
            oUser.set_user_birth(result[User.USERBIRTH])  
            oUser.set_user_sign(result[User.USERSIGN])  
            oUser.set_user_sex(result[User.USERSEX])  
            oUser.set_user_nick_name(result[User.USERNICKNAME])  
            oUser.set_created(result[User.CREATED])  
            oUser.set_user_last_login_ip(result[User.USERLASTLOGINIP])  
            oUser.set_user_last_login_time(result[User.USERLASTLOGINTIME])  
            oUser.set_user_is_online(result[User.USERISONLINE])  
            oUser.set_check_flag(result[User.CHECKFLAG])  
            oUser.set_search_flag(result[User.SEARCHFLAG])  
            oUser.set_user_province(result[User.USERPROVINCE])  
            oUser.set_user_area(result[User.USERAREA])  
        return oUser
    
        
         
    
    
    
    
    def getUserInfoById(self, UserId,user=None):
        '''
        取用户详情
        '''
        tmp = None
        Fields = ('Id', 'UserName', 'UserPass', 'UserLevel', 'UserCash', 'UserPhoto', 'UserState',
                  'UserLoginPosX', 'UserLoginPosY', 'UserEmail', 'UserTel', 'UserAge', 'UserBirth',
                  'UserSign', 'UserSex', 'UserNickName', 'Created', 'UserLastLoginIp', 'UserLastLoginTime',
                  'UserIsOnline', 'checkFlag', 'searchFlag', 'UserProvince', 'UserArea'
                  )
        aParam = {
                  Config.S_TABLE:User.TABLE_NAME,
                  Config.S_SEARCHFIELDS:",".join(Fields),
                  Config.S_SEARCHCONDITION:" Id=%s" % UserId,
                  Config.S_RESULTROW:1,
                  }
        
        result = self.getFieldByCondition(aParam)
        if(result != None):
            if not user:            
                oUser = User();
            else:
                oUser=user;
            oUser.set_user_id(result[User.USERID])  
            oUser.set_user_name(result[User.USERNAME])  
            oUser.set_user_pass(result[User.USERPASS])  
            oUser.set_user_level(result[User.USERLEVEL])  
            oUser.set_user_cash(result[User.USERCASH])  
            oUser.set_user_photo(result[User.USERPHOTO])  
            oUser.set_user_state(result[User.USERSTATE])  
            oUser.set_user_login_pos_x(result[User.USERLOGINPOSX])  
            oUser.set_user_login_pos_y(result[User.USERLOGINPOSY])  
            oUser.set_user_email(result[User.USEREMAIL])  
            oUser.set_user_tel(result[User.USERTEL])  
            oUser.set_user_age(result[User.USERAGE])  
            oUser.set_user_birth(result[User.USERBIRTH])  
            oUser.set_user_sign(result[User.USERSIGN])  
            oUser.set_user_sex(result[User.USERSEX])  
            oUser.set_user_nick_name(result[User.USERNICKNAME])  
            oUser.set_created(result[User.CREATED])  
            oUser.set_user_last_login_ip(result[User.USERLASTLOGINIP])  
            oUser.set_user_last_login_time(result[User.USERLASTLOGINTIME])  
            oUser.set_user_is_online(result[User.USERISONLINE])  
            oUser.set_check_flag(result[User.CHECKFLAG])  
            oUser.set_search_flag(result[User.SEARCHFLAG])  
            oUser.set_user_province(result[User.USERPROVINCE])  
            oUser.set_user_area(result[User.USERAREA])  
        return oUser
    
    def checkUserExistsById(self, UserId):
        '''
        根据Id检测用户是否存在
        @param UserId:int    
        @return:bool
        '''
        return self.__checkExists(User.USERID, UserId)
    def cgPassword(self, UserId, UserPassword, UserNewPassword):
        '''
        用户更改密码
        @param UserId:int
        @param UserPassword:string
        @param UserNewPassword:string  
        @return: int 
        '''
        aParam={Config.S_TABLE:User.TABLE_NAME,
                        Config.S_SEARCHFIELDS:"`%s`='%s'"%(User.USERPASS,UserNewPassword),
                        Config.S_SEARCHCONDITION:"`%s`='%s'"%(User.USERID,UserId)
        }
        self.doUpdate(aParam)
        return Config.I_USER_CHANGE_PASSWORD_OK
    def checkIsUserFriend(self,UserId,FriendId):
        """
        检测一个用户是否是另一个用户的好友
        """
        aParam = {
              Config.S_TABLE:UserFriendsRelation.TABLE_NAME,
              Config.S_SEARCHFIELDS:" `%s` "%(UserFriendsRelation.PRIMARY_KEY),
              Config.S_SEARCHCONDITION:" `%s`=%s AND `%s`=%s " % (UserFriendsRelation.TOUSERID,FriendId,
                    UserFriendsRelation.FROMUSERID,UserId),
              Config.S_RESULTROW:1,
              Config.S_FETCH_ALL:False   #是否要取出全部信息，为否则须带入limit
        }
        return self.getFieldByCondition(aParam)        
    def addNewFriend(self,UserId,FriendId):
        """
        添加一个新好友,成功则返回Last_insert_id
        """
        if(self.checkIsUserFriend(UserId,FriendId)==None):
            values = (
                      UserFriendsRelation.FROMUSERID,UserId,
                      UserFriendsRelation.TOUSERID,FriendId,
                      UserFriendsRelation.CREATED,Func.getNow(),
             )
            
            aParam={
                    Config.S_TABLE:UserFriendsRelation.TABLE_NAME,
                    Config.S_SEARCHFIELDS:"`%s`='%s',`%s`='%s',`%s`='%s' "%values,
            }
                
            return self.doInsert(aParam) 
        else:
            return Config.I_SYS_ZERO
    def delFriend(self,UserId,FriendId):
        """
        删除一个好友
        """
        aParam = {
                   Config.S_TABLE:UserFriendsRelation.TABLE_NAME,
                   Config.S_SEARCHCONDITION:" `%s`=%s AND `%s`=%s " %  (UserFriendsRelation.TOUSERID,FriendId,
                    UserFriendsRelation.FROMUSERID,UserId),
         }
        return self.doDelete(aParam)
    def getUserFriendsById(self,UserId):
        '''
        返回用户的好友信息
        @param UserId:string    要查询的用户信息
        @return: list    用户好友的详细信息列表
        '''
#        getFirendsIdSql = "SELECT `%s` FROM %s WHERE `%s`=%s"
        aParam = {
              Config.S_TABLE:User.TABLE_NAME,
              Config.S_SEARCHFIELDS:" * ",
              Config.S_SEARCHCONDITION:" `%s` in ( SELECT `%s` FROM %s WHERE `%s`=%s ) " % (User.PRIMARY_KEY, UserFriendsRelation.TOUSERID,UserFriendsRelation.TABLE_NAME,
                    UserFriendsRelation.FROMUSERID,UserId),
              Config.S_RESULTROW:1000,
              Config.S_FETCH_ALL:True   #是否要取出全部信息，为否则须带入limit
        }
        return self.getFieldByCondition(aParam)
#        Sql = " SELECT * FROM %s WHERE %s in( SELECT `%s` FROM %s WHERE `%s`=%s)"
#        Sql = Sql %(User.TABLE_NAME,User.PRIMARY_KEY,UserFriendsRelation.TOUSERID,UserFriendsRelation.TABLE_NAME,
#                    UserFriendsRelation.FROMUSERID,UserId)
#        Func.debugInfo(Sql)
#        return self.findAll(Sql)
    def regNewUser(self, UserEmail, UserPassword):
        '''
        注册新用户
        @param UserEmail:string
        @param UserPassword:string
        @return:tuple
        '''
        returnValue = (Config.I_SYS_ZERO,Config.I_USER_REGISTER_USERNAME_FOUND)
        if(not self.checkUserExistsByUserName(UserEmail)):
            values = (User.USERNAME,UserEmail,
                      User.USEREMAIL,UserEmail,
                      User.USERNICKNAME,UserEmail,
                      User.USERPASS,UserPassword,
                      User.CREATED,Func.getNow(),
             )
            
            aParam={Config.S_TABLE:User.TABLE_NAME,
                    Config.S_SEARCHFIELDS:"`%s`='%s',`%s`='%s',`%s`='%s',`%s`='%s',`%s`='%s'"%values,
            }
            returnValue =(self.doInsert(aParam),Config.I_USER_REGISTER_OK)
                
        return returnValue 
    def checkUserExistsByUserName(self, UserName):
        '''
        检测用户是否存在
        @param UserName:string
        @return: bool 
        '''
        return self.__checkExists(User.USERNAME, UserName)
    def checkUserTelExists(self, UserTel):
        return self.__checkExists(User.USERTEL, UserTel)
    def checkUserEmailExists(self, UserEmail):
        return self.__checkExists(User.USEREMAIL, UserEmail)
    def checkUserNickNameExists(self, UserNickName,UserId=None):
        return self.__checkExists(User.USERNICKNAME, UserNickName)
    def __checkExists(self, FieldName, FieldValue):
        
        aParam = {
                  Config.S_TABLE:User.TABLE_NAME,
                  Config.S_SEARCHFIELDS:"`%s`,`%s`"%(User.USERID,FieldName),
                  Config.S_SEARCHCONDITION:" `%s`='%s' " % (FieldName, FieldValue),
                  Config.S_RESULTROW:1,
        }

        return self.getFieldByCondition(aParam)

    def modifanInfo(self, oUser):
        '''
        修改信息
        @param oUser:User 
        @return: tuple
        '''
        if(not oUser):

            return (Config.I_USER_NOT_FOUND,oUser)
        tmp = self.checkUserNickNameExists(oUser.get_user_nick_name())
        if(tmp):
            if( (str(tmp[User.USERID])!=str(oUser.get_user_id()))):
                return (Config.I_USER_NICK_NAME_FOUND,oUser)
        values = (User.USERNICKNAME,oUser.get_user_nick_name(),
                     User.USERAGE,oUser.get_user_age(),
                     User.USERPROVINCE,oUser.get_user_province(),
                     User.USERAREA,oUser.get_user_area(),
                     User.USERSIGN,oUser.get_user_sign(),
        )
        aParam={Config.S_TABLE:User.TABLE_NAME,
                Config.S_SEARCHFIELDS:"`%s`='%s',`%s`='%s',`%s`='%s',`%s`='%s',`%s`='%s'"%values,
                Config.S_SEARCHCONDITION:"`%s`='%s'"%(User.USERID,oUser.get_user_id())
        }
        self.doUpdate(aParam)
        return (Config.I_USER_MODIFAN_INFO_OK,oUser)
    def checkLogin(self,userName,userPass):
        '''
        用户登录
        @param userName:string
        @param userPass:string
        @return:User  
        '''
        aParam = {
                  Config.S_TABLE:User.TABLE_NAME,
                  Config.S_SEARCHFIELDS:"*",
                  Config.S_SEARCHCONDITION:"`%s`='%s'  " % (User.USEREMAIL,userName),
                  Config.S_RESULTROW:1,
        }
        result = self.getFieldByCondition(aParam) 
        if(not result):
            return (Config.I_USER_NOT_FOUND,None)
        if(userPass==result[User.USERPASS]):
            oUser = User()
            oUser.set_user_id(result[User.USERID])  
            oUser.set_user_name(result[User.USERNAME])  
            oUser.set_user_pass(result[User.USERPASS])  
            oUser.set_user_level(result[User.USERLEVEL])  
            oUser.set_user_cash(result[User.USERCASH])  
            oUser.set_user_photo(result[User.USERPHOTO])  
            oUser.set_user_state(result[User.USERSTATE])  
            oUser.set_user_login_pos_x(result[User.USERLOGINPOSX])  
            oUser.set_user_login_pos_y(result[User.USERLOGINPOSY])  
            oUser.set_user_email(result[User.USEREMAIL])  
            oUser.set_user_tel(result[User.USERTEL])  
            oUser.set_user_age(result[User.USERAGE])  
            oUser.set_user_birth(result[User.USERBIRTH])  
            oUser.set_user_sign(result[User.USERSIGN])  
            oUser.set_user_sex(result[User.USERSEX])  
            oUser.set_user_nick_name(result[User.USERNICKNAME])  
            oUser.set_created(result[User.CREATED])  
            oUser.set_user_last_login_ip(result[User.USERLASTLOGINIP])  
            oUser.set_user_last_login_time(result[User.USERLASTLOGINTIME])  
            oUser.set_user_is_online(result[User.USERISONLINE])  
            oUser.set_check_flag(result[User.CHECKFLAG])  
            oUser.set_search_flag(result[User.SEARCHFLAG])  
            oUser.set_user_province(result[User.USERPROVINCE])  
            oUser.set_user_area(result[User.USERAREA])  
            
            return (Config.I_USER_LOGIN_OK,oUser)
        else:
            return (Config.I_USER_PASSWORD_ERROR,None)
    def deleteUser(self, UserId):
        '''
        删除用户
        '''
        aParam = {
                  Config.S_TABLE:User.TABLE_NAME,
                  Config.S_SEARCHCONDITION:" `%s`='%s'" % (User.USERID, UserId),
        }
        return self.doDelete(aParam)
if __name__=="__main__":
    mUser = UserModel()
#    print mUser.checkUserExistsByUserName("geminiblue")
#    print mUser.checkUserExistsById(5)
#    print mUser.cgPassword(5,'dsfdsfdsdsfaf', 'dsfdsfdsaf')
#    print mUser.regNewUser('geminiblue1@qq.com','1234567')
#    print mUser.deleteUser(5)
    
#    mUser.addNewFriend(10,9)
    test = mUser.getUserFriendsById(10)
    mUser.delFriend(10,13)
    print test
